package com.example.weight.greenSeasons.deodorization;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class DeodorizationTower extends AppCompatActivity {

    private String name, factory, type, radioText, subUrl;

    private EditText jiayaoTime, jiashuiTime, yaojiName, penzuiGuanluCleanTime,
            penzuiGuanluCleanStatus, tianliaoCleanTime, tianliaoChangeTime, comment;

    private RadioButton yes, no;
    private boolean flag = false;
    private String id = "";

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flocculation_tower);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        type = previousIntent.getStringExtra("type");
        if (type.equals("flocculation"))
            subUrl = "1";
        else if (type.equals("kitchen"))
            subUrl = "2";

        TitleBar titleBar = findViewById(R.id.main_navigation_titleBar);
        if (type.equals("flocculation"))
            titleBar.setTitle("絮凝除臭塔运行记录表");
        else if (type.equals("kitchen"))
            titleBar.setTitle("厨余除臭塔运行记录表");
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        jiayaoTime = findViewById(R.id.xuning_tower_jiayao_time);
        jiashuiTime = findViewById(R.id.xuning_tower_jiashui_time);
        yaojiName = findViewById(R.id.xuning_tower_yaojimingcheng);
        penzuiGuanluCleanTime = findViewById(R.id.xuning_tower_qingxishijian);
        penzuiGuanluCleanStatus = findViewById(R.id.xuning_tower_qingxiqingkuang);
        tianliaoCleanTime = findViewById(R.id.xuning_tower_tianliao_qingxishijian);
        tianliaoChangeTime = findViewById(R.id.xuning_tower_tianlao_genghuanshijian);
        comment = findViewById(R.id.xuning_tower_comment);
        yes = findViewById(R.id.xuning_tower_radio_true);
        no = findViewById(R.id.xuning_tower_radio_false);

        TextView dateText = findViewById(R.id.deodorization_tower_date);
        String tempText = dateText.getText().toString();
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = c.get(Calendar.DAY_OF_MONTH);
        dateText.setText(tempText+year+"-"+month+"-"+day);

        RadioGroup radioGroup = findViewById(R.id.xuning_tower_radio_group);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton button = findViewById(checkedId);
            radioText = button.getText().toString();
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/SjqFlocculationKitchenDeodorizationRunning/getLast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {

                                JSONObject data = jsonObject.getJSONObject("data");
                                String test = data.getString("dosingTime"+subUrl);
                                if (!test.equals("null")) {
                                    new AlertDialog.Builder(DeodorizationTower.this)
                                            .setTitle("今日已填写此表")
                                            .setCancelable(false)
                                            .setPositiveButton("确定", null)
                                            .show();
                                    jiayaoTime.setText(data.getString("dosingTime"+subUrl));
                                    jiashuiTime.setText(data.getString("waterTime"+subUrl));
                                    yaojiName.setText(data.getString("drugName"+subUrl));
                                    String radioText = data.getString("isScaleMark"+subUrl);
                                    if (radioText.equals("是")) yes.setChecked(true);
                                    else no.setChecked(true);
                                    penzuiGuanluCleanTime.setText(data.getString("nozzlePipelineCleanTime"+subUrl));
                                    penzuiGuanluCleanStatus.setText(data.getString("nozzlePipelineCleanCondition"+subUrl));
                                    tianliaoCleanTime.setText(data.getString("packingCleaningTime"+subUrl));
                                    tianliaoChangeTime.setText(data.getString("packingReplacementTime"+subUrl));
                                    comment.setText(data.getString("remarks"));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DeodorizationTower.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        jiayaoTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(DeodorizationTower.this, 2,
                        (view1, hourOfDay, minute) ->
                                jiayaoTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        jiayaoTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });

        jiashuiTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(DeodorizationTower.this, 2,
                        (view1, hourOfDay, minute) ->
                                jiashuiTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        jiashuiTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });

        penzuiGuanluCleanTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(DeodorizationTower.this, 2,
                        (view1, hourOfDay, minute) ->
                                penzuiGuanluCleanTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        penzuiGuanluCleanTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });

        tianliaoCleanTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(DeodorizationTower.this, 2,
                        (view1, hourOfDay, minute) ->
                                tianliaoCleanTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        tianliaoCleanTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });

        tianliaoChangeTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(DeodorizationTower.this, 2,
                        (view1, hourOfDay, minute) ->
                                tianliaoChangeTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        tianliaoChangeTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectJiayaoTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                jiayaoTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectJiashuiTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                jiashuiTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectPenzuiGuanluCleanTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                penzuiGuanluCleanTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectTianliaoCleanTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                tianliaoCleanTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectTianliaoChangeTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                tianliaoChangeTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    public void save(View view) {
        if (jiayaoTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写加药时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (jiashuiTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写加水时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (yaojiName.getText().toString().equals("")) {
            Toast.makeText(this, "请填写药剂名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (radioText.equals("")) {
            Toast.makeText(this, "请选择是否到规定线", Toast.LENGTH_SHORT).show();
            return;
        }
        if (penzuiGuanluCleanTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写喷嘴、管路清洗时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (penzuiGuanluCleanStatus.getText().toString().equals("")) {
            Toast.makeText(this, "请填写喷嘴、管路清洗情况", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tianliaoCleanTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写填料清洗时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tianliaoChangeTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写填料更换时间", Toast.LENGTH_SHORT).show();
            return;
        }


        if (subUrl.equals("2")){
            RequestQueue queue = Volley.newRequestQueue(this);
            String url = Config.url + "/sjq/SjqFlocculationKitchenDeodorizationRunning/getLastByName?factory="+factory+"&operator="+name;
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (!jsonObject.isNull("data")) {
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    Log.d("jy",data.toString());
                                    id=data.getString("id");
                                    flag = true;
                                }else {
                                    Toast.makeText(DeodorizationTower.this,"请先填写絮凝除臭塔数据 ", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(DeodorizationTower.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    return;
                }
            });
//            {
//                @Override
//                protected Map<String, String> getParams() {
//                    Map<String, String> map = new HashMap<>();
//                    map.put("operator", name);
//                    map.put("factory", factory);
//                    return map;
//                }
//            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(stringRequest);
        }

        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/SjqFlocculationKitchenDeodorizationRunning/addForm" + subUrl;
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")) {
                                            Toast.makeText(DeodorizationTower.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        } else
                                            Toast.makeText(DeodorizationTower.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DeodorizationTower.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map = new HashMap<>();
                            if (flag){
                                map.put("id" , id);
                            }
                            map.put("dosingTime" + subUrl, jiayaoTime.getText().toString());
                            map.put("waterTime" + subUrl, jiashuiTime.getText().toString());
                            map.put("drugName" + subUrl, yaojiName.getText().toString());
                            map.put("isScaleMark" + subUrl, radioText);
                            map.put("nozzlePipelineCleanTime" + subUrl, penzuiGuanluCleanTime.getText().toString());
                            map.put("nozzlePipelineCleanCondition" + subUrl, penzuiGuanluCleanStatus.getText().toString());
                            map.put("packingCleaningTime" + subUrl, tianliaoCleanTime.getText().toString());
                            map.put("packingReplacementTime" + subUrl, tianliaoChangeTime.getText().toString());
                            map.put("operator", name);
                            map.put("remarks", comment.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}